package com.yida.auth.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.yida.auth.form.LoginUKeyBody;
import com.yida.auth.service.SysUKeyLoginService;
import com.yida.common.core.domain.R;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.utils.sign.RsaUtils;
import com.yida.common.security.service.TokenService;
import com.yida.system.api.model.LoginUser;

/**
 * Ukey登录 token 控制
 * 
 * @author hmh
 * @date 2023/03/28
 */
@RestController
public class UKeyTokenController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUKeyLoginService sysUKeyLoginService;

    @PostMapping("uKeySignMsg")
    public R<?> uKeySignMsg(@RequestBody LoginUKeyBody form) throws Exception {
        if (StringUtils.isNull(form.getUsername())) {
            return R.fail("用户名不能为空！");
        }
        if (!sysUKeyLoginService.checkUkey()) {
            return R.fail("600", "ukey校验未启用！请尝试使用其他方式登录！");
        }
        Map<String, String> resultMap = sysUKeyLoginService.waitSignMsg(form.getUsername(), form.getUkeyId());
        if (resultMap.size() > 0) {
            return R.ok(resultMap);
        }
        return R.fail("600", "ukey校验失败！请尝试使用其他方式登录！");
    }

    @PostMapping("uKeylogin")
    public R<?> login(@RequestBody LoginUKeyBody form) throws Exception {
        LoginUser userInfo = null;
        String passwordInfo = RsaUtils.decryptByPrivateKey(form.getPassword());
        if (sysUKeyLoginService.checkUkey()) {
            userInfo = sysUKeyLoginService.login(form.getUsername(), passwordInfo, form.getUkeyId(), form.getRnd(), form.getSignUKeyStr());
        }
        if (userInfo == null) {
            return R.fail("当前未开启UKey验证，请使用其他方式登录！");
        }
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

}
